import { defineComponent, ref, onMounted, onUnmounted, nextTick, warn } from 'vue';
import * as pdfjsLib from 'pdfjs-dist';
import { useRoute } from 'vue-router';
import styles from './PdfViewer.module.less';

// 配置pdfjs worker - 修正版
// 对于pdfjs-dist 5.x版本，应该使用CDN路径或直接引用构建文件

pdfjsLib.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.js', window.location.origin).toString();
// pdfjsLib.GlobalWorkerOptions.workerSrc = "/node_modules/pdfjs-dist/build/pdf.worker.js";

export default defineComponent({
  name: 'PdfViewer',
  setup() {
    const route = useRoute();
    const pdfContainer = ref(null);
    const canvasRef = ref(null);
    const loading = ref(true);
    const error = ref('');
    const currentPage = ref(1);
    const totalPages = ref(0);
    const zoom = ref(1.0);
    let pdfDoc = null;

    // 加载PDF文件
    const loadPdf = async () => {
      try {
        loading.value = true;
        error.value = '';
        
        // 从路由的query参数中获取url
        // const pdfUrl = route.query.url;
        const pdfUrl = `${import.meta.env.VITE_APP_BASE_URL}/${decodeURIComponent(route.query.url)}` ;
        
        
        if (!pdfUrl) {
          throw new Error('没有提供PDF文件URL');
        }

        console.log('加载PDF文件:', pdfUrl);
        
        // 使用pdfjsLib加载PDF
        const loadingTask =  pdfjsLib.getDocument(pdfUrl);
        console.warn('加载任务:', loadingTask);
        
        pdfDoc = await loadingTask.promise;
        warn('PDF文档:', pdfDoc);
        totalPages.value = pdfDoc.numPages;
        
        // 渲染第一页
        await renderPage(currentPage.value);
      } catch (err) {
        console.error('加载PDF失败:', err);
        error.value = `加载PDF失败: ${err.message || '未知错误'}`;
      } finally {
        loading.value = false;
      }
    };

    // 渲染指定页码
    const renderPage = async (pageNum) => {
        console.warn('渲染页码:', pageNum);
        
      if (!pdfDoc || pageNum < 1 || pageNum > totalPages.value) {
        return;
      }

      try {
        const page = await pdfDoc.getPage(pageNum);
        const viewport = page.getViewport({ scale: zoom.value });
        
        // 设置canvas尺寸
        const canvas = canvasRef.value;
        const context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        // 渲染PDF页面到canvas
        const renderContext = {
          canvasContext: context,
          viewport: viewport
        };
        
        await page.render(renderContext).promise;
        currentPage.value = pageNum;
      } catch (err) {
        console.error('渲染页面失败:', err);
        error.value = `渲染页面失败: ${err.message || '未知错误'}`;
      }
    };

    // 上一页
    const prevPage = () => {
      if (currentPage.value > 1) {
        renderPage(currentPage.value - 1);
      }
    };

    // 下一页
    const nextPage = () => {
      if (currentPage.value < totalPages.value) {
        renderPage(currentPage.value + 1);
      }
    };

    // 缩放控制
    const zoomIn = () => {
      zoom.value += 0.1;
      renderPage(currentPage.value);
    };

    const zoomOut = () => {
      if (zoom.value > 0.2) {
        zoom.value -= 0.1;
        renderPage(currentPage.value);
      }
    };

    // 跳转到指定页码
    const goToPage = (pageNum) => {
      const num = parseInt(pageNum);
      if (!isNaN(num) && num >= 1 && num <= totalPages.value) {
        renderPage(num);
      }
    };

    // 组件挂载时加载PDF
    onMounted(() => {
      nextTick(() => {
        loadPdf();
      });
    });

    // 组件卸载时清理资源
    onUnmounted(() => {
      if (pdfDoc) {
        pdfDoc.destroy();
      }
    });

    return {
      styles,
      pdfContainer,
      canvasRef,
      loading,
      error,
      currentPage,
      totalPages,
      zoom,
      prevPage,
      nextPage,
      zoomIn,
      zoomOut,
      goToPage
    };
  },
  render() {
    return (
      <div class={this.styles['pdf-viewer']}>
        <div class={this.styles['pdf-header']}>
          <h2>PDF查看器</h2>
        </div>
        
        {this.loading && (
          <div class={this.styles['loading']}>
            <div class={this.styles['loading-spinner']}></div>
            <span>加载中...</span>
          </div>
        )}
        
        {this.error && (
          <div class={this.styles['error-message']}>{this.error}</div>
        )}
        
        <div class={this.styles['pdf-container']} ref="pdfContainer">
          <canvas ref="canvasRef"></canvas>
        </div>
        
        <div class={this.styles['pdf-controls']}>
          <button onClick={this.prevPage} disabled={this.currentPage <= 1}>
            上一页
          </button>
          
          <div class={this.styles['page-info']}>
            <input
              type="number"
              value={this.currentPage}
              onChange={(e) => this.goToPage(e.target.value)}
              min="1"
              max={this.totalPages}
            />
            <span>/ {this.totalPages}</span>
          </div>
          
          <button onClick={this.nextPage} disabled={this.currentPage >= this.totalPages}>
            下一页
          </button>
          
          <button onClick={this.zoomOut} disabled={this.zoom <= 0.2}>
            缩小
          </button>
          
          <button onClick={this.zoomIn}>
            放大
          </button>
        </div>
      </div>
    );
  }
});